package com.gee.spring.cloud.aerospace.simulate.core.satellite.telemetry.task;

import com.gee.spring.cloud.aerospace.simulate.core.satellite.telemetry.common.SateTraceContext;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author gee
 * @since 2025/5/15 10:45
 */
@Service
public class TmManager {

    private Map<String, SateTraceContext> sateTraceContextMap = new ConcurrentHashMap<String, SateTraceContext>();

    public boolean start(SateTraceContext sateTraceContext) {
        SateTraceContext oldContext = sateTraceContextMap.get(sateTraceContext.getTraceKey());
        Optional.ofNullable(oldContext).ifPresent(context->
                context.getTmArcHandler().doStop(context, Instant.now().toEpochMilli()));
        sateTraceContextMap.put(sateTraceContext.getTraceKey(), sateTraceContext);
        sateTraceContext.getTmArcHandler().start(sateTraceContext, Instant.now().toEpochMilli());
        return true;
    }

    public boolean stop() {
        sateTraceContextMap.values().forEach(context -> {
            context.getTmArcHandler().stop(context, Instant.now().toEpochMilli());
        });
        sateTraceContextMap.clear();
        return true;
    }

    public boolean pause() {
        sateTraceContextMap.values().forEach(context -> {
            context.getTmArcHandler().pause(context, Instant.now().toEpochMilli());
        });
        return true;
    }

    public boolean resume() {
        sateTraceContextMap.values().forEach(context -> {
            context.getTmArcHandler().resume(context, Instant.now().toEpochMilli());
        });
        return true;
    }

}
